package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.To.BoundsTo;
import com.atguigu.common.To.SkuHasStockVo;
import com.atguigu.common.To.SkuReductionTo;
import com.atguigu.common.To.es.SkuEsModel;
import com.atguigu.common.constan.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.SpuboundsFeign;
import com.atguigu.gulimall.product.feign.wareFeign;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 *
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    SpuboundsFeign spuboundsFeign;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductAttrValueService attrValueService;
    @Autowired
    wareFeign warefeign;
    @Autowired
    SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    /**
     * 保存spu信息和sku信息 发布商品
     * @param spuInfo
     */
    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuInfo) {
        //1.保存spu基本信息 `pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2.保存spu的描述图片  pms_spu_info_desc
        //2.1）获取图片信息
        List<String> decript = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescService.saveSpuInfoBatch(spuInfoDescEntity);
        //3.保存spu图片集 pms_spu_images
        List<String> images = spuInfo.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(),images);

        //4.保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(atrr -> {
            ProductAttrValueEntity attrEntity = new ProductAttrValueEntity();
            //根据id查询attr的信息
            AttrEntity byId = attrService.getById(atrr.getAttrId());
            attrEntity.setAttrName(byId.getAttrName()); //名字
            attrEntity.setAttrId(atrr.getAttrId()); //id
            attrEntity.setAttrValue(atrr.getAttrValues()); //值
            attrEntity.setSpuId(spuInfoEntity.getId()); //spuid
            attrEntity.setQuickShow(byId.getShowDesc());
            return attrEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        //5.保存spu的积分信息
        Bounds bounds = spuInfo.getBounds();
        BoundsTo boundsTo = new BoundsTo();
        BeanUtils.copyProperties(bounds,boundsTo);
        boundsTo.setSpuId(spuInfoEntity.getId());
        R save = spuboundsFeign.save(boundsTo);
        if (save.getcode()!=0){
            log.error("远程保存sku积分失败");
        }
        //6.保存当前spu对应的sku的基本信息
        //6.1）sku的基本信息  pms_sku_info
        List<Skus> skus = spuInfo.getSkus();
        if (skus!=null&&skus.size()>0){
            skus.forEach((Skus skus1) -> {
                String DefaultImg = "";
                for (Images images1 : skus1.getImages()) {
                    if (images1.getDefaultImg()==1){
                        DefaultImg = images1.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                    BeanUtils.copyProperties(skus1,skuInfoEntity);
                    skuInfoEntity.setSpuId(spuInfoEntity.getId());
                    skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                    skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                    skuInfoEntity.setSaleCount(0L);
                    skuInfoEntity.setSkuDefaultImg(DefaultImg); //默认图片
                //保存sku信息
                skuInfoService.save(skuInfoEntity);
                List<SkuImagesEntity> collect1 = skus1.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entiy->{
                return !StringUtils.isEmpty(entiy.getImgUrl());
                }
                ).collect(Collectors.toList());
                //6.2）sku的图片信息  pms_sku_images
                skuImagesService.saveBatch(collect1);
                //6.3）sku的销售属性  pms_sku_sale_attr_value
                List<Attr> attr = skus1.getAttr();
                List<SkuSaleAttrValueEntity> collect2 = attr.stream().map(attr1 -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr1,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect2);
                //6.4）sku的优惠属性  gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(skus1,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                spuboundsFeign.saveSkuReduction(skuReductionTo);
            });
        }

    }

    /**
     * spu检索 分页查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageList(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)){
            wrapper.and(wap->{
                wap.eq("id",key).or().like("spu_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void  productUp(Long spuId) {
        //根据spu查询sku的信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.selectList(spuId);
        List<Long> collect1 = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询当前sku所有可以用来检索的规格属性
        List<ProductAttrValueEntity> attrValueEntities = attrValueService.baseAttrlistforspu(spuId);
        List<Long> collect = attrValueEntities.stream().map(attvalue -> {
            return attvalue.getAttrId();
        }).collect(Collectors.toList());

        //根据attrid查询
        List<Long> search = attrService.selectSeach(collect);
        Set<Long> idSet = new HashSet<>(search);
        List<SkuEsModel.Attrs> attrsList = attrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //发送远程调用 查询库存系统是否有库存
        Map<Long, Boolean> collect2 = null;
        try {
            R skuStock = warefeign.findSkuStock(collect1);
            TypeReference<List<SkuHasStockVo>> listTypeReference = new TypeReference<List<SkuHasStockVo>>(){};
            collect2 = skuStock.getData(listTypeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("远程调用异常");
        }

        //遍历sku
        Map<Long, Boolean> finalCollect = collect2;
        List<SkuEsModel> collect3 = skuInfoEntities.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //设置是否有库存
            if (finalCollect == null) {
                skuEsModel.setHasStock(true);
            } else {
                Boolean aBoolean = finalCollect.get(skuInfoEntity.getSkuId());
                skuEsModel.setHasStock(aBoolean);
            }
            //查询品牌
            BrandEntity byId = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());
            //查询分类
            CategoryEntity byId1 = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(byId1.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //保存到es中
        R r = searchFeignService.save(collect3);
        Integer getcode = r.getcode();
        int code = ProductConstant.statusEnum.SPU_UP.getCode();
        if(getcode==0){
            //上架成功
            baseMapper.updateStauts(spuId, code);
        }
    }

    /**
     * 更具skuId查询spu信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoSkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }
}